/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
class Solution {
    fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
        
        var li1 = l1
        var li2 = l2
        
        var r: ListNode? = null
        var c: ListNode? = null
        while(li1 != null || li2 != null) {
            val t = findMin(li1, li2)
            if (c == null) {
                c = ListNode(t.first)
                r = c
            } else {
                c.next = ListNode(t.first)
                c = c.next
            }
            
            li1 = t.second
            li2 = t.third
        }
        return r
    }
    
    fun findMin(l1: ListNode?, l2: ListNode?) =
        if (l1 == null) {
            Triple(l2!!.`val`, l1, l2.next)
        } else  if (l2 == null) {
         Triple(l1!!.`val`, l1.next, l2)
        } else if (l1.`val` < l2.`val`) {
             Triple(l1.`val`, l1.next, l2)
        } else {
             Triple(l2.`val`, l1, l2.next)
        }
        
}